/*
 *  Copyright (C) 2010 Zubanov Dmitry
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


/**
 *
 * @author Zubanov Dmitry aka javadimon, zubanov@gmail.com
 * Omsk, Russia, created 29.05.2010
 * (C) Copyright by Zubanov Dmitry
 */

package org.jssdb.core.event;

import java.lang.reflect.Method;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Zubanov Dmitry aka javadimon, zubanov@gmail.com
 * Omsk, Russia,
 * created 25.03.2010
 */
public class EventSource extends Observable {

    private static EventSource self = null;
    private static final Logger logger = Logger.getLogger(EventSource.class.getName());

    public static EventSource getInstance(){
        if(self == null){
            self = new EventSource();
        }

        return self;
    }

    public void addOserverClass(String className){
        try {
            Class cls = Class.forName(className);

            for (Method method : cls.getMethods()) {
                if (method.getName().equals("getInstance")) {
                     Object obj = method.invoke(cls, new Object[]{});
                     addObserver((Observer) obj);
                     logger.log(Level.INFO, "adding Observer to class {0}", cls.getName());
                }

                if (method.getName().equals("findInstance")) {
                     Object obj = method.invoke(cls, new Object[]{});
                     addObserver((Observer) obj);
                     logger.log(Level.INFO, "adding Observer to class {0}", cls.getName());
                }
            }
        } catch (Exception ex) {
            logger.log(Level.SEVERE, className, ex);
        }
    }

    public void removeObserverClass(String className){
        // TODO
    }

    public void fireCustomEvent(Object evt) {
        setChanged();
        notifyObservers(evt);
    }
}
